import koa from "koa";
import json from "koa-json";
import onerror from "koa-onerror";
import bodyparser from "koa-bodyparser";
import logger from "koa-logger";
import helmet from "koa-helmet";
import indexRouter from "./routes";
import eventRouter from "./routes/event";
import cors from "./middlewares/cors";
import dataSetRouter from "./routes/data-set";

import("./analysis/index").then(
  ({ splitLogFileTimed, analysisLogsTimed, rmLogsTimed }) => {
    splitLogFileTimed();
    analysisLogsTimed();
    rmLogsTimed();
  },
);

const app = new koa();

app.use(helmet());

app.use(cors);

onerror(app);

// middlewares
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  }),
);
app.use(json());

app.use(logger());

// routes
app.use(indexRouter.routes()).use(indexRouter.allowedMethods());
app.use(eventRouter.routes()).use(eventRouter.allowedMethods());
app.use(dataSetRouter.routes()).use(dataSetRouter.allowedMethods());

// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

export default app;
